package com.gan.simple_init.quartz.controller;


import com.gan.simple_init.annotation.OperLog;
import com.gan.simple_init.common.base.PageRequest;
import com.gan.simple_init.common.base.ResponseResult;
import com.gan.simple_init.common.base.RestResultGenerator;
import com.gan.simple_init.common.constant.CommonConstant;
import com.gan.simple_init.common.constant.UserConstant;
import com.gan.simple_init.common.enums.BusinessType;
import com.gan.simple_init.common.exception.BusinessException;
import com.gan.simple_init.quartz.model.SysJob;
import com.gan.simple_init.quartz.model.dto.SysJobAddDTO;
import com.gan.simple_init.quartz.model.dto.SysJobDTO;
import com.gan.simple_init.quartz.model.dto.SysJobUpdateDTO;
import com.gan.simple_init.quartz.service.SysJobService;
import com.gan.simple_init.quartz.util.JobStatusEnum;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;

/**
 * job控制器
 * @author gbw
 */
@RestController
@RequestMapping("/job")
@Slf4j
public class SysJobController {

    @Resource
    private SysJobService sysJobService;

    @PreAuthorize(UserConstant.PRE_ROLE_NAME_ADMIN)
    @OperLog(title = "获取任务列表", businessType = BusinessType.GET)
    @PostMapping("/list")
    @ApiOperation(value = "获取任务列表")
    public ResponseResult<?> list(@RequestBody PageRequest pageRequest) throws BusinessException {
        try {
            // 查询列表数据
            return RestResultGenerator.success(sysJobService.listSysJob(pageRequest));
        } catch (Exception e) {
            log.error("执行" + this.getClass().getSimpleName()+ ":" + new Exception().getStackTrace()[0].getMethodName());
            throw e;
        }
    }

    @PreAuthorize(UserConstant.PRE_ROLE_NAME_ADMIN)
    @OperLog(title = "修改任务", businessType = BusinessType.UPDATE)
    @ApiOperation(value = "修改任务")
    @PostMapping("/update")
    public ResponseResult<?> edit(@RequestBody SysJobUpdateDTO sysJobUpdateDTO) throws BusinessException {
        try {
            SysJob jobServer = sysJobService.get(sysJobUpdateDTO.getJobId());
            if (jobServer == null){
                throw new BusinessException("查询不到该任务!");
            }
            if (CommonConstant.IsValid.VALID.equals(jobServer.getIsValid())) {
                return RestResultGenerator.error("修改之前请先停止任务!");
            }
            SysJob sysJob = new SysJob();
            BeanUtils.copyProperties(sysJobUpdateDTO, sysJob);
            sysJobService.validJob(sysJob);
            sysJobService.updateById(sysJob);
            return RestResultGenerator.success("操作成功");
        }  catch (Exception e) {
            log.error("执行" + this.getClass().getSimpleName()+ ":" + new Exception().getStackTrace()[0].getMethodName());
            throw e;
        }
    }

    @PreAuthorize(UserConstant.PRE_ROLE_NAME_ADMIN)
    @OperLog(title = "修改任务状态", businessType = BusinessType.UPDATE)
    @ApiOperation(value = "修改状态，isValid=1表示启动，isValid=0表示停止")
    @GetMapping("/status")
    public ResponseResult<?> changeStatus(@RequestParam Long id, @RequestParam String isValid) throws BusinessException {
        try {
            sysJobService.changeStatus(id, isValid);
            return RestResultGenerator.success("操作成功");
        }  catch (Exception e) {
            log.error("执行" + this.getClass().getSimpleName()+ ":" + new Exception().getStackTrace()[0].getMethodName());
            throw e;
        }
    }

    @PreAuthorize(UserConstant.PRE_ROLE_NAME_ADMIN)
    @OperLog(title = "单个删除任务", businessType = BusinessType.DELETE)
    @ApiOperation(value = "单个删除")
    @GetMapping("/delete")
    public ResponseResult<?> remove(@RequestParam Long id) throws BusinessException {
        try {
            SysJob jobServer = sysJobService.get(id);
            if (CommonConstant.IsValid.VALID.equals(jobServer.getIsValid())) {
                return RestResultGenerator.error("删除前请先停止任务！");
            }
            sysJobService.remove(id);
            return RestResultGenerator.success("操作成功");
        }  catch (Exception e) {
            log.error("执行" + this.getClass().getSimpleName()+ ":" + new Exception().getStackTrace()[0].getMethodName());
            throw e;
        }
    }

    @PreAuthorize(UserConstant.PRE_ROLE_NAME_ADMIN)
    @OperLog(title = "立即运行单个任务", businessType = BusinessType.DELETE)
    @ApiOperation(value = "立即运行")
    @GetMapping("/run")
    public ResponseResult<?> run(@RequestParam Long id) throws BusinessException {
        try {
            SysJob job = sysJobService.get(id);
            sysJobService.run(job);
            return RestResultGenerator.success("操作成功");
        }  catch (Exception e) {
            log.error("执行" + this.getClass().getSimpleName()+ ":" + new Exception().getStackTrace()[0].getMethodName());
            throw e;
        }
    }

    @PreAuthorize(UserConstant.PRE_ROLE_NAME_ADMIN)
    @OperLog(title = "删除任务，支持批量删除", businessType = BusinessType.DELETE)
    @ApiOperation(value = "删除任务，支持批量删除")
    @GetMapping("/removeBatch")
    public ResponseResult<?> removeBatch(@RequestParam Long[] ids) throws BusinessException {
        try {
            for (Long id : ids) {
                SysJob jobServer = sysJobService.get(id);
                if (JobStatusEnum.RUNNING.getCode().equals(jobServer.getJobStatus())) {
                    return RestResultGenerator.error("删除前请先停止任务！");
                }
            }
            sysJobService.removeBatch(ids);
            return RestResultGenerator.success("操作成功");
        } catch (Exception e) {
            log.error("执行" + this.getClass().getSimpleName()+ ":" + new Exception().getStackTrace()[0].getMethodName());
            throw e;
        }
    }

    @PreAuthorize(UserConstant.PRE_ROLE_NAME_ADMIN)
    @OperLog(title = "批量暂停任务", businessType = BusinessType.OTHER)
    @ApiOperation(value = "批量暂停任务")
    @GetMapping("/pauseBatch")
    public ResponseResult<?> pauseBatch(@RequestParam Long[] ids) throws BusinessException {
            sysJobService.pauseBatch(ids);
            return RestResultGenerator.success("操作成功");
    }

    @PreAuthorize(UserConstant.PRE_ROLE_NAME_ADMIN)
    @OperLog(title = "批量恢复任务", businessType = BusinessType.OTHER)
    @ApiOperation(value = "批量恢复任务")
    @GetMapping("/resumeBatch")
    public ResponseResult<?> resumeBatch(@RequestParam Long[] ids) throws BusinessException {
        sysJobService.resumeBatch(ids);
        return RestResultGenerator.success("操作成功");
    }

    @PreAuthorize(UserConstant.PRE_ROLE_NAME_ADMIN)
    @OperLog(title = "新增任务", businessType = BusinessType.INSERT)
    @ApiOperation(value = "新增任务，需要填写的字段有beanClass、cronExpression、description、jobGroup、jobName")
    @PostMapping("/add")
    public ResponseResult<?> add(@RequestBody SysJobAddDTO sysJobAddDTO) throws BusinessException {
        try {
            SysJob sysJob = new SysJob();
            if (sysJobAddDTO != null){
                BeanUtils.copyProperties(sysJobAddDTO,sysJob);
            }
            sysJobService.validJob(sysJob);
            sysJobService.save(sysJob);
            return RestResultGenerator.success("操作成功");
        }  catch (Exception e) {
            log.error("执行" + this.getClass().getSimpleName()+ ":" + new Exception().getStackTrace()[0].getMethodName());
            throw e;
        }
    }

}
